#include "utilc_api.h"

#if defined(WINDOWS_IMPL)
#include <windows.h>
#include <time.h>
#include <direct.h>

int getpid() {
    return GetCurrentProcessId();
}

int gettid() {
    return GetCurrentThreadId();
}

void sleep(uint32_t seconds) {
    Sleep(seconds*1000);
}

time_t timegm (struct tm *__tp) {
    return _mkgmtime(__tp);
}

void setworkpath2ex() {
    int i=0;
    char buffer[MAX_PATH];
    GetModuleFileNameA( NULL, buffer, MAX_PATH);
    for(i=strlen(buffer)-1; i>0; i--) {
        if(buffer[i]=='\\' || buffer[i]=='/') {
            buffer[i]=0;
            break;
        }
    }
    _chdir(buffer);
}

void setworkpath(char* path) {
    _chdir(path);
}

char* getpathex(char* path) {
    int i=0;
    char buffer[MAX_PATH];
    GetModuleFileNameA( NULL, buffer, MAX_PATH);
    for(i=strlen(buffer)-1; i>0; i--) {
        if(buffer[i]=='\\' || buffer[i]=='/') {
            buffer[i]=0;
            break;
        }
    }
    strcpy(path, buffer);
    return buffer;
}

char* getpathdl(char* path) {
    int i=0;
    char buffer[MAX_PATH];
    GetModuleFileNameA( NULL, buffer, MAX_PATH);
    for(i=strlen(buffer)-1; i>0; i--) {
        if(buffer[i]=='\\' || buffer[i]=='/') {
            buffer[i]=0;
            break;
        }
    }
    strcpy(path, buffer);
    return buffer;
}

void util_sleep(uint32_t seconds) {
    Sleep(seconds*1000);
}

void util_sleep2(uint32_t milliSeconds) {
    Sleep(milliSeconds);
}

#endif

#if defined(LINUX_IMPL)
#define __USE_GNU
#include <unistd.h>
#include <pthread.h>
#include <pwd.h>
#include <dirent.h>
#include <dlfcn.h>

int gettid() {
    return pthread_self();
}

_UTILC_API void Sleep(uint32_t milliSeconds) {
    usleep(milliSeconds*1000);
}

void setworkpath2ex() {
    char exePath[PATH_MAX];
    memset(exePath, 0, sizeof(exePath));
    readlink("/proc/self/exe", exePath, sizeof(exePath));

    dirname(exePath);
    chdir(exePath);
}

void setworkpath(char* path) {
    chdir(path);
}

char* getpathex(char* path) {
    char exePath[PATH_MAX];
    memset(exePath, 0, sizeof(exePath));
    readlink("/proc/self/exe", exePath, sizeof(exePath));

    dirname(exePath);
    strcpy(path, exePath);
    return path;
}

static void empty_dladdr() {}
char* getpathdl(char* path) {
    Dl_info dl_info;
    dladdr((void*)empty_dladdr, &dl_info);
    strcpy(path, dl_info.dli_fname);
    return path;
}

void util_sleep(uint32_t seconds) {
    sleep(seconds);
}

void util_sleep2(uint32_t milliSeconds) {
    usleep(milliSeconds*1000);
}
#endif